<?php
/**
 * User: gli
 * Date: 13-3-11
 * Time: 8:25 PM
 */
class Project extends Base {

	protected function init() {
		parent::init();

		$this->attributes['uid'] = 0;
	}

	public function __construct($id=null) {
		$this->init();

		if (!empty($id)) {
			if ($id instanceof stdClass) {
				if (!$this->load($id->id)) {
					throw new Exception("Fail to load project object.");
				}
			} else if ($id instanceof Project) {
				foreach ($id->attributes as $key => $value) {
					$this->attributes[$key] = $value;
				}
			} else if (is_numeric($id)) {
				if (!$this->load($id)) {
					throw new Exception("Fail to load project by given id: $id");
				}
			} else {
				throw new InvalidParameterException("Invalid parameter exception: Unrecognised Value.");
			}
		}
	}

	/**
	 * Load project object by given id
	 *
	 * @param int $id
	 *
	 * @return bool
	 */
	protected function load($id) {
		$row = get_project_object_as_row($id);
		if ($row) {
			$obj_array = (array) $row;
			foreach ($obj_array as $key => $value) {
				$this->attributes[$key] = $value;
			}
			return true;
		}

		return false;
	}
}

/**
 * Create or update the project
 * @param int $id project id
 * @param int $uid user id
 * @param int $created created time
 * @param int $updated updated time
 *
 * @return bool|int
 */
function create_project($id, $uid, $created, $updated) {
	$id = (int) $id;
	$uid = (int) $uid;
	$created = (int) $created;
	$updated = (int) $updated;

	$row = get_project_object_as_row($id);
	if ($row) {
		// update
		$updatedTime = time();
		$query = "UPDATE projects SET $updated={$updatedTime}";
	} else {
		// create new project
		if ($uid) {
			$time = time();
			$query = "INSERT INTO projects(uid, created, updated) VALUES($uid, $time, $time)";
			return insert_data($query);
		}
	}
	return false;
}

/**
 * Get project by given id
 * @param int $id project id
 * @return object|bool project object
 */
function get_project_object_as_row($id) {
	$id = (int) $id;
	if (!$id) return false;

	$query = "SELECT * FROM projects WHERE id={$id} LIMIT 1";
	return get_data_row($query);
}

/**
 * Get project object by given id
 * @param int $id given project id
 *
 * @return Project|false
 */
function get_project_by_id($id) {
	$id = (int) $id;
	if (!$id) return false;

	return new Project($id);
}

/**
 * Get projects by given user id
 * @param int $uid user id
 * @param int $offset offset for pagination, default 0.
 * @param int $limit limit for pagination, default 1.
 *
 * @return array|bool
 */
function get_projects_by_user_id($uid, $offset=0, $limit=1) {
	$uid = (int) $uid;
	$offset = (int) $offset;
	if ($offset < 0) $offset = 0;
	$limit = (int) $limit;
	if ($limit <= 0) $limit = 1;
	$query = "SELECT * FROM projects WHERE uid={$uid} LIMIT {$offset}, {$limit}";
	return get_data($query);
}